#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "CView/CTableView.h"
#include "CModel/CModel.h"
#include "CDelegate/CDelegate.h"


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    _pTableView(new CTableView(this)),
    _pModel(new CModel())
{
    ui->setupUi(this);
    this->setWindowTitle("Custom MVC");
    this->setCentralWidget(_pTableView);
    this->setContentsMargins(0, 0, 0, 0);
    _pTableView->setModel(_pModel);

    this->initUi();

    this->resize(1024, 768);
}

MainWindow::~MainWindow()
{
    delete ui;
    delete _pModel;
    delete _pTableView;
}

void MainWindow::initUi()
{
    int colCount = _pModel->columnCount(_pModel->index(0, 0));
    _pTableView->resizeColumnsToContents();
    for (int i=0; i<colCount; ++i) {
        _pTableView->setColumnWidth(i, 300);
    }

    COpratorDelegate *pCOD = new COpratorDelegate(_pTableView, COpratorDelegate::MULBTN);
    pCOD->setCModel(_pModel);
    _pTableView->setItemDelegateForColumn(colCount - 1, pCOD);
    auto *pModel = _pTableView->model();
    int row = pModel->rowCount();
    for (int i=0; i<row; ++i) {
        _pTableView->openPersistentEditor(pModel->index(i, colCount - 1));
    }
    _columns.append(colCount - 1);

    COpratorDelegate *pProcessCOD = new COpratorDelegate(_pTableView, COpratorDelegate::PROGRESSBAR);
    pProcessCOD->setCModel(_pModel);
    _pTableView->setItemDelegateForColumn(colCount - 2, pProcessCOD);
    for (int i=0; i<row; ++i) {
        _pTableView->openPersistentEditor(pModel->index(i, colCount - 2));
    }
    _columns.append(colCount - 2);


    COpratorDelegate *pCbxCOD = new COpratorDelegate(_pTableView, COpratorDelegate::COMBOBOX);
    pCbxCOD->setCModel(_pModel);
    _pTableView->setItemDelegateForColumn(colCount - 3, pCbxCOD);
    for (int i=0; i<row; ++i) {
        _pTableView->openPersistentEditor(pModel->index(i, colCount - 3));
    }
    _columns.append(colCount - 3);

    connect(_pTableView, &CTableView::filterUpdate, this,  &MainWindow::openPersistentForColumns );
}

void MainWindow::openPersistentForColumns()
{
    auto *pModel = _pTableView->model();
    int row = _pModel->rowCount();
    for (int i=0; i<row; ++i) {
        for (int &col : _columns) {
            _pTableView->openPersistentEditor(pModel->index(i, col));
        }
    }
}
